import { Poll } from '@/entities/poll.entity';
import { PageSingerItemtDto } from '../../dto/singer/singer.dto';
import { Singer } from '../../entities/singer.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';

@Injectable()
export class SingerService {
  constructor(
    @InjectRepository(Singer)
    private singerRepository: Repository<Singer>,

    @InjectRepository(Poll)
    private voteRepository: Repository<Poll>,
  ) {}

  // 创建歌手
  async createSinger(singerData: Partial<Singer>): Promise<Singer> {
    const singer = this.singerRepository.create(singerData);
    return await this.singerRepository.save(singer);
  }

  // 获取所有歌手
  async getAllSingers(): Promise<Singer[]> {
    return await this.singerRepository.find();
  }
  // 根据项目id获取所有歌手
  async getPollIdAllSingers(pollId: string): Promise<any> {
    return await this.singerRepository.find({
      where: { poll: { id: pollId } },
    });
  }

  /**
   * 分页条件用户信息
   */
  async page(param: PageSingerItemtDto): Promise<[Singer[], number]> {
    const { pageSize, pageNo, id, name, musicName } = param;
    const where: any = {};
    if (id) where.id = id;
    if (name) where.name = Like(`%${name}%`);
    if (musicName) where.musicName = Like(`%${musicName}%`);

    const [voteList, total] = await this.singerRepository.findAndCount({
      where,
      order: {
        createdTime: 'DESC',
      },
      relations: ['poll', 'voteRecords'],
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });

    // 将角色信息筛选为所需字段

    const result = voteList.map((vote) => {
      const { poll, voteRecords, ...voteList } = vote; // 将投票信息和歌手信息分离

      return { ...voteList, poll, voteRecords };
    });

    return [voteList, total];
  }

  // 根据ID获取歌手
  async getSingerById(id: string): Promise<Singer> {
    return await this.singerRepository.findOne({ where: { id } });
  }

  // 更新歌手信息
  async updateSinger(updateData: Partial<Singer>): Promise<Singer> {
    const singer = await this.singerRepository.findOne({
      where: { id: updateData.id },
    });
    if (!singer) {
      throw new Error('Singer not found');
    }
    const updatedSinger = Object.assign(singer, updateData);
    return await this.singerRepository.save(updatedSinger);
  }

  // 删除歌手
  async deleteSinger(id: string): Promise<void> {
    const singer = await this.singerRepository.findOne({ where: { id } });
    if (!singer) {
      throw new Error('Singer not found');
    }
    await this.singerRepository.delete(id);
  }
}
